<template>
	<view>
		<u-picker v-model="showTimePicker" @confirm="confirmTimePicker" mode="time" :params="timePickerParams"></u-picker>
		<u-popup mode="bottom" v-model="showSelect" v-if="selectIndex !== false" height="560" border-radius="14">
			<u-radio-group :wrap="true" @change="selectRadioChange(fields[selectIndex].name)" v-model="form[fields[selectIndex].name]">
				<view class="select-radio-item" v-for="(cc, cidx) in fields[selectIndex].values_list" :key="cidx">
					<u-radio shape="circle" :name="cidx">{{ cc }}</u-radio>
				</view>
			</u-radio-group>
		</u-popup>
		<u-popup mode="bottom" v-model="showSelects" height="560" border-radius="14">
			<view class="selects-top">
				<view @click="selectsConfirm('cancel')" class="selects-cancel">取消</view>
				<view @click="selectsConfirm('confirm')" class="selects-confirm">确认</view>
			</view>
			<u-checkbox-group :max="selectsItemMax">
				<view class="select-box" v-for="(item, index) in selectsList" :key="index">
					<u-checkbox
						v-model="item.checked"
						:name="item.name"
					>
						<view class="select-item">{{item.label}}</view>
					</u-checkbox>
				</view>
			</u-checkbox-group>
		</u-popup>
		<u-picker mode="region" v-model="regionShow" @confirm="regionConfirm"></u-picker>
		<block v-for="(item, index) in fields" :key="index">
			<u-form-item v-if="item.type_list == 'string'" :label="item.title" :prop="item.name">
				<u-input v-model="form[item.name]" @input="fieldChange" :value="item.value" :placeholder="item.notice ? item.notice:'请输入' + item.title" />
			</u-form-item>
			<u-form-item v-if="item.type_list == 'textarea' || item.type_list == 'editor'" :label="item.title" :prop="item.name">
				<u-input v-model="form[item.name]" @input="fieldChange" type="textarea" :placeholder="item.notice ? item.notice:'请输入' + item.title" />
			</u-form-item>
			<u-form-item v-if="item.type_list == 'text'" :label="item.title" :prop="item.name">
				<view class="form-text">{{item.value}}</view>
			</u-form-item>
			<u-form-item v-if="item.type_list == 'number'" :label="item.title" :prop="item.name">
				<u-input v-model="form[item.name]" type="digit" @input="fieldChange" :placeholder="item.notice ? item.notice:'请输入' + item.title" />
			</u-form-item>
			<u-form-item v-if="item.type_list == 'date' || item.type_list == 'time' || item.type_list == 'datetime'" :label="item.title" :prop="item.name">
				<view v-if="form[item.name]" @click="showTimePickerFun(index)">{{form[item.name]}}</view>
				<view v-else class="form-placeholder-style" @click="showTimePickerFun(index)">{{item.notice ? item.notice:'请选择' + item.title}}</view>
			</u-form-item>
			<u-form-item v-if="item.type_list == 'select'" :label="item.title" :prop="item.name">
				<view v-if="form[item.name]" @click="showSelectFun(index)">{{fields[index].values_list[form[item.name]]}}</view>
				<view v-else class="form-placeholder-style" @click="showSelectFun(index)">{{item.notice ? item.notice:'请选择' + item.title}}</view>
			</u-form-item>
			<u-form-item v-if="item.type_list == 'selects'" :label="item.title" :prop="item.name">
				<view v-if="form[item.name]" @click="showSelectsFun(index)">{{form[item.name]}}</view>
				<view v-else class="form-placeholder-style" @click="showSelectsFun(index)">{{item.notice ? item.notice:'请选择' + item.title}}</view>
			</u-form-item>
			<u-form-item v-if="item.type_list == 'image' || item.type_list == 'images'" label-position="left" :label="item.title" :prop="item.name">
				<u-upload
					:index="item.name"
					@on-success="imgUploadSuccess"
					@on-remove="imgUploadRemove"
					:max-count="(item.type_list == 'image') ? 1:(item.maximum ? item.maximum:9)"
					:header="uploadHeader"
					name="file"
					:size-type="['original']"
					:action="fileAction"
					:form-data="uploadFormData"
					:file-list="fileList" ></u-upload>
			</u-form-item>
			<u-form-item v-if="item.type_list == 'file' || item.type_list == 'files'" :label="item.title" :prop="item.name">
				<!-- #ifndef APP-PLUS -->
				<uni-file-picker 
					:name="item.name"
				    v-model="formFile[item.name]"
					fileMediatype="all"
					mode="grid" 
					:limit="(item.type_list == 'file') ? 1:(item.maximum ? item.maximum:9)"
					:auto-upload="false"
					@select="fileSelect"
					@delete="fileDelete"
				/>
				<!-- #endif -->
				<!-- #ifdef APP-PLUS -->
				<uni-file-picker
					:name="item.name"
				    v-model="formFile[item.name]"
					fileMediatype="video"
					mode="grid" 
					:limit="(item.type_list == 'file') ? 1:(item.maximum ? item.maximum:9)"
					:auto-upload="false"
					@select="fileSelect"
					@delete="fileDelete"
				/>
				<!-- #endif -->
			</u-form-item>
			<u-form-item v-if="item.type_list == 'switch'" label-position="left" :label="item.title" :prop="item.name">
				<u-switch @change="fieldChange" v-model="form[item.name]" slot="right"></u-switch>
			</u-form-item>
			<u-form-item v-if="item.type_list == 'checkbox'" :label="item.title" :prop="item.name">
				<u-checkbox-group @change="checkboxChange(index)">
					<view class="select-box" v-for="(cc, cidx) in item.values_list" :key="cidx">
						<u-checkbox
							v-model="cc.checked"
							:name="cc.name"
						>
							<view class="select-item">{{cc.label}}</view>
						</u-checkbox>
					</view>
				</u-checkbox-group>
			</u-form-item>
			<u-form-item v-if="item.type_list == 'radio'" :label="item.title" :prop="item.name">
				<u-radio-group @change="fieldChange" v-model="form[item.name]">
					<u-radio shape="circle" v-for="(cc, cidx) in item.values_list" :key="cidx" :name="cidx">{{ cc }}</u-radio>
				</u-radio-group>
			</u-form-item>
			<u-form-item v-if="item.type_list == 'city'" :label="item.title" :prop="item.name">
				<u-input type="select" :select-open="regionShow" v-model="form[item.name]" :placeholder="item.notice ? item.notice:'请选择' + item.title" @click="regionShowFun(index)"></u-input>
			</u-form-item>
		</block>
	</view>
</template>

<script>
	import woConfig from "../../common/config.js"; // 本地配置数据
	var timePickerItem = null, selectsItem = null, files = {}, regionItem = null;
	export default {
		name:"form-field",
		props: {
			fields: {
				type: [Object, Array],
				required: true,
				default: {}
			},
			form: {
				type: Object,
				required: true
			},
			formFile: {
				type: Object,
				required: true,
				default: {}
			}
		},
		data () {
			return {
				showTimePicker: false,
				timePickerParams: {
					year: false,
					month: false,
					day: false,
					hour: false,
					minute: false,
					second: false
				},
				showSelect: false,
				selectIndex: false,
				showSelects: false,
				selectsItemMax: 1,
				selectsList: [],
				uploadHeader: {},
				uploadFormData: {},
				fileAction: '',
				fileList: [],
				regionShow: false
			}
		},
		mounted: function () {
			var userinfo = uni.getStorageSync('userinfo');
			this.fileAction = woConfig.baseUrl + '/api/common/upload';
			this.uploadHeader = {
				token: userinfo ? userinfo.token:''
			}
			
			this.$u.api.uploadMultipart().then(res => {
				if (res.data.multipart) {
					let mu = new Object();
					for (let i in res.data.multipart) {
						mu[i] = res.data.multipart[i]
					}
					this.uploadFormData = mu
					this.fileAction = res.data.uploadurl
				}
			}).catch(res => {
				this.$u.toast('获取文件上传API失败，请重试！');
			})
		},
		methods: {
			fieldChange: function () {
				this.$emit('update:form', this.form)
			},
			showTimePickerFun: function (idx) {
				timePickerItem = this.fields[idx]
				this.showTimePicker = true
				if (timePickerItem.type_list == 'datetime') {
					for (let t in this.timePickerParams) {
						this.timePickerParams[t] = true
					}
					return true;
				}
				
				for (let t in this.timePickerParams) {
					this.timePickerParams[t] = false
				}
				if (timePickerItem.type_list == 'date') {
					this.timePickerParams.year = this.timePickerParams.month = this.timePickerParams.day = true
				} else if (timePickerItem.type_list == 'time') {
					this.timePickerParams.hour = this.timePickerParams.minute = this.timePickerParams.second = true
				}
			},
			confirmTimePicker: function (value) {
				if (timePickerItem.type_list == 'datetime') {
					this.form[timePickerItem.name] = value.year + '-' + value.month + '-' + value.day + ' ' + value.hour + ':' + value.minute + ':' + value.second
				} else if (timePickerItem.type_list == 'date') {
					this.form[timePickerItem.name] = value.year + '-' + value.month + '-' + value.day
				} else if (timePickerItem.type_list == 'time') {
					this.form[timePickerItem.name] = value.hour + ':' + value.minute + ':' + value.second
				}
				this.$emit('update:form', this.form)
				this.$emit('clearError', timePickerItem.name, 'all')
			},
			showSelectFun: function (idx) {
				this.showSelect = true
				this.selectIndex = idx
			},
			selectRadioChange: function (name) {
				this.$emit('clearError', name, 'all')
				this.$emit('update:form', this.form)
				this.showSelect = false
			},
			showSelectsFun: function (idx) {
				selectsItem = this.fields[idx]
				this.showSelects = true
				this.selectsItemMax = selectsItem.maximum ? selectsItem.maximum:999
				let slist = [], selected = this.form[selectsItem.name].split(',')
				for (let v in selectsItem.values_list) {
					slist.push({
						name: v,
						checked: selected.includes(v),
						label: selectsItem.values_list[v]
					})
				}
				this.selectsList = slist
			},
			selectsConfirm: function (type) {
				let ids = ''
				for (let t in this.selectsList) {
					if (type == 'confirm') {
						if (this.selectsList[t].checked) {
							ids += this.selectsList[t].name + ','
						}
					} else {
						this.selectsList[t].checked = false
					}
				}
				this.showSelects = false
				this.form[selectsItem.name] = ids ? ids.slice(0, ids.length-1):''
				this.$emit('clearError', selectsItem.name, 'all')
				this.$emit('update:form', this.form)
			},
			imgUploadListHandle: function (lists, name) {
				let files = [];
				for (let f in lists) {
					if (lists[f].progress == 100) {
						files.push(lists[f].response.data.fullurl)
					}
				}
				this.form[name] = files.join(',')
				this.$emit('clearError', name, 'all')
				this.$emit('update:form', this.form)
			},
			imgUploadRemove: function (index, lists, name) {
				this.imgUploadListHandle(lists, name)
			},
			imgUploadSuccess: function (data, index, lists, name) {
				this.imgUploadListHandle(lists, name)
			},
			fileSelect: function (file){
				if (!files[file.name]) {
					files[file.name] = []
				}
				
				for (let f in file.tempFiles) {
					this.upload(file.tempFiles[f], (res) => {
						this.form[file.name] += res.data.fullurl + ','
						this.$emit('update:form', this.form)
					}, file.name)
					files[file.name].push(file.tempFiles[f].path)
				}
			},
			fileDelete: function (file) {
				for (let f in files[file.name]) {
					if (files[file.name][f] == file.tempFile.path) {
						files[file.name].splice(files[file.name].indexOf(files[file.name][f]), 1);
					}
				}
				this.form[file.name] = files[file.name].join(',')
				this.$emit('update:form', this.form)
			},
			upload: function (file, callBack, name) {
				var that = this
				uni.showLoading({
					title: '正在上传...'
				})
				
				const uploadTask = uni.uploadFile({
					url: that.fileAction,
					header: that.uploadHeader,
					// #ifdef APP-PLUS || H5
					file: file,
					// #endif
					filePath: file.path,
					name: 'file',
					formData: that.uploadFormData,
					success: (uploadFileRes) => {
						uni.hideLoading()
						let res = JSON.parse(uploadFileRes.data);
						if (res.code == 1) {
							callBack(res, file)
						} else {
							uni.showModal({
								title: '温馨提示',
								content: res.msg,
								showCancel: false
							})
						}
					},
					fail: res => {
						uni.hideLoading()
						uni.showModal({
							title: '温馨提示',
							content: '上传失败,请重试~',
							showCancel: false
						})
					},
					complete: res => {
						that.$emit('clearError', name, 'all')
						uni.hideLoading()
					}
				});
				
				// #ifndef APP-PLUS
				uploadTask.onProgressUpdate((res) => {
					uni.showLoading({
						title: res.progress + '%'
					})
				});
				// #endif
			},
			checkboxChange: function (idx) {
				let checked = []
				for (let v in this.fields[idx].values_list) {
					if (this.fields[idx].values_list[v].checked) {
						checked.push(this.fields[idx].values_list[v].name)
					}
				}
				this.form[this.fields[idx].name] = checked ? checked.join(','):''
				this.$emit('update:form', this.form)
				this.$emit('update:fields', this.fields)
			},
			regionShowFun: function (idx) {
				this.regionShow = true
				regionItem = this.fields[idx]
			},
			regionConfirm(e) {
				this.form[regionItem.name] = e.province.label + '/' + e.city.label + '/' + e.area.label;
				this.$emit('update:form', this.form)
			},
		}
	}
</script>

<style>
.form-text {
	font-size: 30rpx;
	line-height: 38rpx;
	color: #1A1A1A;
}
.selects-top {
	display: flex;
	height: 80rpx;
	line-height: 80rpx;
	padding: 0 26rpx;
}
.selects-confirm {
	margin-left: auto;
	color: #007AFF;
}
.select-box {
	display: flex;
	padding: 20rpx;
	width: 100%;
}
.select-item {
	display: block;
	line-height: 36rpx;
	padding-left: 10rpx;
}
.select-radio-item {
	display: flex;
	height: 80rpx;
	flex-wrap: wrap;
	width: 100%;
	align-items: center;
	padding-left: 20rpx;
}
.form-placeholder-style {
	color: #C0C4CC;
}
</style>
